/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.isfd.constant.enums.IsfdMetadataTableNameEnum;
import com.comac.ins.isfd.domain.bo.IsfdMetadataBusinessRefDatabaseBo;
import com.comac.ins.isfd.domain.bo.IsfdMetadataManagementBo;
import com.comac.ins.isfd.domain.vo.*;
import com.comac.ins.isfd.domain.vo.blood.BloodRelationshipInnerVo;
import com.comac.ins.isfd.domain.vo.blood.BloodRelationshipOuterVo;
import com.comac.ins.isfd.domain.vo.blood.BloodRelationshipVo;
import com.comac.ins.isfd.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IsfdMetadataManagementAnalysisServiceImpl implements IIsfdMetadataManagementAnalysisService {
    @Autowired
    private IIsfdMetadataBusinessSceneDefinitionService iIsfdMetadataBusinessSceneDefinitionService;
    @Autowired
    private IIsfdMetadataDatabaseService iIsfdMetadataDatabaseService;
    @Autowired
    private IIsfdMetadataBusinessRefDatabaseService iIsfdMetadataBusinessRefDatabaseService;
    @Autowired
    private IIsfdMetadataManagementService isfdMetadataManagementService;
    @Autowired
    private IIsfdMetadataManagementSheetService iIsfdMetadataManagementSheetService;


    @Override
    public IsfdMetadataBusinessSceneDefinitionVo getInfo(Long businessId) {
        IsfdMetadataBusinessSceneDefinitionVo isfdMetadataBusinessSceneDefinitionVo = iIsfdMetadataBusinessSceneDefinitionService.queryById(businessId);
        //只计算二层的children（不用递归，不会存在第三层）的数据库数据入库数量总和
        List<IsfdMetadataBusinessSceneDefinitionVo> children = isfdMetadataBusinessSceneDefinitionVo.getChildren();
        for (IsfdMetadataBusinessSceneDefinitionVo child : children) {
            List<IsfdMetadataDatabaseVo> databaseVoList = child.getDatabaseVoList();
            for (IsfdMetadataDatabaseVo isfdMetadataDatabaseVo : databaseVoList) {
                IsfdMetadataManagementBo bo = new IsfdMetadataManagementBo();
                bo.setBusinessId(businessId);
                bo.setDatabaseId(isfdMetadataDatabaseVo.getId());
                List<IsfdMetadataManagementVo> isfdMetadataManagementVoList = isfdMetadataManagementService.queryList(bo);
                isfdMetadataDatabaseVo.setInventoryCount(isfdMetadataManagementVoList.stream().mapToLong(IsfdMetadataManagementVo::getInventoryCount).sum());
            }
        }
        return isfdMetadataBusinessSceneDefinitionVo;
    }

    @Override
    public List<String> queryManagementIds(Long businessId, Long databaseId) {
        IsfdMetadataManagementBo bo = new IsfdMetadataManagementBo();
        bo.setBusinessId(businessId);
        bo.setDatabaseId(databaseId);
        List<String> result = new ArrayList<>();
        List<IsfdMetadataManagementVo> isfdMetadataManagementVoList = isfdMetadataManagementService.queryList(bo);
        if (CollectionUtils.isEmpty(isfdMetadataManagementVoList)) {
            return result;
        }
        result = isfdMetadataManagementVoList.stream().map(IsfdMetadataManagementVo::getId).collect(Collectors.toList());
        return result;
    }

    @Override
    public BloodRelationshipVo bloodRelationship(Long businessId, Long databaseId) {
        // 1.校验
        IsfdMetadataBusinessSceneDefinitionVo isfdMetadataBusinessSceneDefinitionVo = iIsfdMetadataBusinessSceneDefinitionService.queryById(businessId);
        if (isfdMetadataBusinessSceneDefinitionVo == null || isfdMetadataBusinessSceneDefinitionVo.getIsDeleted() == 1) {
            throw new BaseException("业务场景定义不存在，请确认后重试！");
        }
        IsfdMetadataDatabaseVo isfdMetadataDatabaseVo = iIsfdMetadataDatabaseService.queryById(databaseId);
        if (isfdMetadataDatabaseVo == null || isfdMetadataDatabaseVo.getIsDeleted() == 1) {
            throw new BaseException("要素数据库不存在，请确认后重试！");
        }
        IsfdMetadataBusinessRefDatabaseBo isfdMetadataBusinessRefDatabaseBo = new IsfdMetadataBusinessRefDatabaseBo();
        isfdMetadataBusinessRefDatabaseBo.setIsDeleted(0L);
        isfdMetadataBusinessRefDatabaseBo.setBusinessId(businessId);
        isfdMetadataBusinessRefDatabaseBo.setDatabaseId(databaseId);
        List<IsfdMetadataBusinessRefDatabaseVo> isfdMetadataBusinessRefDatabaseVoList = iIsfdMetadataBusinessRefDatabaseService.queryList(isfdMetadataBusinessRefDatabaseBo);
        if (CollectionUtils.isEmpty(isfdMetadataBusinessRefDatabaseVoList)) {
            throw new BaseException("业务场景关联的要素数据库不存在，请确认后重试！");
        }

        // 2.获取元数据管理sheet记录数据
        IsfdMetadataManagementBo isfdMetadataManagementBo = new IsfdMetadataManagementBo();
        isfdMetadataManagementBo.setBusinessId(businessId);
        isfdMetadataManagementBo.setDatabaseId(databaseId);
        List<IsfdMetadataManagementVo> isfdMetadataManagementVoList = isfdMetadataManagementService.queryList(isfdMetadataManagementBo);
        List<String> managementIds = isfdMetadataManagementVoList.stream().map(IsfdMetadataManagementVo::getId).collect(Collectors.toList());
        List<IsfdMetadataManagementSheetVo> isfdMetadataManagementSheetVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(managementIds)) {
            isfdMetadataManagementSheetVoList = iIsfdMetadataManagementSheetService.queryListByManagementIds(managementIds);
        }

        // 3.封装 库层
        BloodRelationshipVo result = new BloodRelationshipVo();
        result.setDatabaseName(isfdMetadataDatabaseVo.getName());
        result.setDatabaseType(isfdMetadataDatabaseVo.getDatabaseType());
        // level的值
        Integer level = IsfdMetadataTableNameEnum.checkOutDatabaseTypeAndReturnLevel(isfdMetadataDatabaseVo.getDatabaseType());
        result.setLevel(level);
        List<BloodRelationshipOuterVo> outerList = new ArrayList<>();
        String[] tableNames = isfdMetadataDatabaseVo.getStorageLocation().split(",");
        for (String tableName : tableNames) {
            // 4.封装outer层
            BloodRelationshipOuterVo outerVo = new BloodRelationshipOuterVo();
            outerVo.setTableName(IsfdMetadataTableNameEnum.getTableNameByLevel(tableName, level));

            // 5.封装inner层
            List<BloodRelationshipInnerVo> innerList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(isfdMetadataManagementSheetVoList)) {
                List<IsfdMetadataManagementSheetVo> targetSheetVoList = isfdMetadataManagementSheetVoList.stream().filter(sheetVo -> sheetVo.getTableName().equals(tableName)).toList();
                if (CollectionUtils.isNotEmpty(targetSheetVoList)) {
                    for (IsfdMetadataManagementSheetVo sheetVo : targetSheetVoList) {
                        BloodRelationshipInnerVo innerVo = new BloodRelationshipInnerVo();
                        innerVo.setCreateTime(sheetVo.getCreateTime());
                        innerVo.setInventoryCount(sheetVo.getInventoryCount());
                        if (IsfdMetadataTableNameEnum.LEVEL_FIVE.equals(level)) {
                            innerVo.setTableName(tableName);
                        }
                        Optional<IsfdMetadataManagementVo> optional = isfdMetadataManagementVoList.stream().filter(mvo -> sheetVo.getMetadataManagementId().equals(mvo.getId())).findFirst();
                        if (optional.isPresent()) {
                            IsfdMetadataManagementVo isfdMetadataManagementVo = optional.get();
                            innerVo.setFileUrl(isfdMetadataManagementVo.getFileUrl());
                            innerVo.setFileName(isfdMetadataManagementVo.getFileName());
                        }
                        innerList.add(innerVo);
                    }
                }
            }
            outerVo.setInnerList(innerList);
            outerList.add(outerVo);
        }
        result.setOuterList(outerList);
        return result;
    }
}
